import { PayloadAction, createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { Picture, apiCreatePicture, apiGetPictureList } from '../../api/picture'
import { AsyncState, ListState } from '..'
import { PagerQuery } from '../../api'
import { apiGetFavoritePictureList } from '../../api/favorite-picture'
type PictureState = AsyncState & ListState<Picture> &{
    current?:Picture
}

const initialState: PictureState = {
    status: 'idle',
    error: null,
    list: [],
    pager: {
        totalRows: 0,
        pageSize: 10,
        page: 1,
    }
}
export const fetchPictures = createAsyncThunk('picture/fetchPictures', apiGetPictureList)
export const fetchFavoritePictures = createAsyncThunk('picture/fetchFavoritePictures', apiGetFavoritePictureList)
export const createPicture = createAsyncThunk('picture/createPicture', apiCreatePicture)
export const detailSlice = createSlice({
    name: 'detail',
    initialState: initialState,
    reducers: {
        detailPagerChange(state, action: PayloadAction<PagerQuery>) {
            state.pager.page = initialState.pager.page
            state.pager.pageSize = initialState.pager.pageSize

            if (action.payload.page) {
                state.pager.page = action.payload.page
            }
            if (action.payload.pageSize) {
                state.pager.pageSize = action.payload.pageSize
            }
            state.status = 'idle'
        },
        detailReset(state) {
            state.status = 'idle'
        },
        changeCurrent(state,action:PayloadAction<number>){
            state.current = state.list.find((i)=> i.id === action.payload)
        }
    },
    extraReducers(builder) {
        builder
            .addCase(fetchPictures.pending, (state) => {
                state.status = 'loading'
            })
            .addCase(fetchPictures.fulfilled, (state, action) => {
                state.status = 'succeeded'
                state.list = action.payload.list
                state.pager = action.payload.pager
            })
            .addCase(fetchPictures.rejected, (state) => {
                state.status = 'failed'
                state.error = '获取详细信息列表失败'
            })
            .addCase(fetchFavoritePictures.pending, (state) => {
                state.status = 'loading'
            })
            .addCase(fetchFavoritePictures.fulfilled, (state, action) => {
                state.status = 'succeeded'
                state.list = action.payload.list
                state.pager = action.payload.pager
            })
            .addCase(fetchFavoritePictures.rejected, (state) => {
                state.status = 'failed'
                state.error = '获取详细信息列表失败'
            })
            .addCase(createPicture.fulfilled, (state) => {
                state.status = 'idle'
            })
    }
})
export const { detailPagerChange, detailReset ,changeCurrent} = detailSlice.actions
export default detailSlice.reducer